import { IKnowledgeList } from '@/types';
import { EditOutlined, CloudDownloadOutlined, SettingOutlined, DeleteOutlined, CloudUploadOutlined, InboxOutlined } from '@ant-design/icons';
import { Popover, Form, Space, Button, Drawer, Pagination, Upload, message, Input, Switch, Image } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { KnowledgeModelState, Link, useDispatch, useSelector } from 'umi';
import styles from './index.less';
const { Dragger } = Upload;
interface Iknowledge {
    knowledgelist: IKnowledgeList,
    page: number
}
const KnowledgeBox: React.FC<Iknowledge> = (props) => {
    const dispatch = useDispatch()
    const content = (
        <div>
            {props.knowledgelist.status === 'publish' ? <span>设为草稿</span> : <span>发布线上</span>}
        </div>
    );

    // 删除功能
    async function delHandleClick() {
        await dispatch({
            type: 'knowledge/delKnowledgeList',
            payload: props.knowledgelist.id
        })
        await dispatch({
            type: 'knowledge/getKnowledgeList',
            payload: { page: props.page }
        })

    }
    // 分页
    const [page, setPage] = useState(1);
    function pageChange(page: number, pageSize: number) {
        setPage(page);

    }

    // 发送请求
    useEffect(() => {
        dispatch({
            type: 'knowledge/getKnowledgeList',
            payload: { page }
        })
    }, [])
    // 获取数据
    const { knowledgeList, knowledgeLength, KnowledgeDrawerFile, KnowledgeDrawerFileLength } = useSelector((state: { knowledge: KnowledgeModelState }) => state.knowledge);

    // 编辑功能
    // 实现新建抽屉效果
    const [visible, setVisible] = useState(false);
    const [childrenDrawer, setChildrenDrawer] = useState(false);
    const showDrawer = () => {
        setVisible(true);
    };
    // 关闭抽屉
    const onClose = () => {
        setVisible(false);
    };

    // 评论开关
    const [check, setChecked] = useState(props.knowledgelist.isCommentable);
    function onChange(checked: any) {
        setChecked(checked);

    }
    // 子盒子开关
    function showChildrenDrawer() {
        setChildrenDrawer(true);
    }
    function onChildrenDrawerClose() {
        setChildrenDrawer(false);

    }
    // 云存储
    // 通过获取之前存储的信息达到取得登录态
    let head = JSON.parse(localStorage.getItem("header") as string);
    // 数据回显
    const myRef = useRef(null);
    const [url, setUrl] = useState(props.knowledgelist.cover);

    // 图片回显
    // 图片回显使用defaultValue 不符合需求，只能够用value
    const propsOver = {
        name: 'file',
        multiple: true,
        headers: {
            Authorization: head
        },
        action: 'https://creationapi.shbwyz.com/api/file/upload?unique=0',
        onChange(info: any) {
            const { status } = info.file;
            if (status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (status === 'done') {
                console.log(info.file, 'info.file....');
                message.success(`${info.file.name} file uploaded successfully.`);
                setUrl(info.file.response.data.url);
            } else if (status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
        onDrop(e: any) {
            console.log('Dropped files', e.dataTransfer.files);
        },
        showUploadList: false
    };
    // 图片上传input框值移除
    function moveOutInputValue() {
        setUrl('');
    }
    // 实现抽屉图文数据获取
    const [DrawPage, setDrawPage] = useState(1);
    function drawerChange(page: number, pageSize: number) {
        setDrawPage(page);
    }
    // 抽屉点击卡片实现 切换图片上传地址
    function changeUrl(params:string){
        setUrl(params);
        setChildrenDrawer(false);
    }
    useEffect(() => {
        dispatch({
            type: 'knowledge/getKnowledgeDrawerList',
            payload: DrawPage
        })
    }, [DrawPage])
    // 创建文字的编辑和禁用切换
    const [Text, changeText] = useState('');
    function titleChange(e: React.ChangeEvent) {
        changeText((e.target as HTMLInputElement).value);
    }
    // 更新功能的实现
    const inputTitle = useRef(null);
    const inputDescribe = useRef(null);

    async function createKnowList() {
        await dispatch({
            type: 'knowledge/updateKnowledgeList',
            payload: {
                cover: (myRef as any).current.input.value,
                isCommentable: check,
                summary: (inputDescribe as any).current.resizableTextArea.props.value,
                title: (inputTitle as any).current.input.value,
                id: props.knowledgelist.id
            }
        });
        await dispatch({
            type: 'knowledge/getKnowledgeList',
            payload: { page }
        })
        setVisible(false);
    }

    return <div className={styles.box}>
        <div>
            <img src={props.knowledgelist.cover} alt="" />
            <div className={styles.textNode}>
                <div>{props.knowledgelist.title}</div>
                <div>{props.knowledgelist.summary}</div>
            </div>
            <div className={styles.btns}>
                <Link to={`/knowledge/editor/${props.knowledgelist.id}`}><EditOutlined /></Link>
                {
                    props.knowledgelist.status === 'publish' ? <Popover content={content} trigger="hover">
                        <CloudDownloadOutlined onClick={async () => {
                            await dispatch({
                                type: 'knowledge/publishOrDrafs',
                                payload: {
                                    status: 'draft',
                                    id: props.knowledgelist.id,
                                }
                            })
                            await dispatch({
                                type: 'knowledge/getKnowledgeList',
                                payload: { page: props.page }
                            })
                        }} />
                    </Popover>
                        : <Popover content={content} trigger="hover">
                            <CloudUploadOutlined onClick={async () => {
                                await dispatch({
                                    type: 'knowledge/publishOrDrafs',
                                    payload: {
                                        status: 'publish',
                                        id: props.knowledgelist.id,
                                    }
                                })
                                await dispatch({
                                    type: 'knowledge/getKnowledgeList',
                                    payload: { page: props.page }
                                })
                            }} />
                        </Popover>
                }

                {/* 点击编辑实现编辑功能 */}
                <SettingOutlined onClick={showDrawer} />
                <DeleteOutlined onClick={delHandleClick} />
                {/* 抽屉 */}
                <Drawer title="更新知识库" placement="right" visible={visible} width={693} extra={
                    <Space>
                        <span onClick={onClose} style={{ fontSize: '20px' }}>x</span>
                    </Space>
                } closable={false}
                    footer={
                        <div className={styles.footer}>

                            <Button onClick={onClose}>
                                取消
                            </Button>
                            {
                                <Button type="primary" onClick={createKnowList}>
                                    更新
                                </Button>
                            }

                        </div>
                    }
                >
                    <div style={{ padding: '24px' }}>
                        <Form onFinish={createKnowList}>

                            <Form.Item name={'title'} label="名称" >
                                <Input onChange={titleChange} ref={inputTitle} defaultValue={props.knowledgelist.title} />
                            </Form.Item>
                            <Form.Item name={'summary'} label="描述">
                                <Input.TextArea ref={inputDescribe} defaultValue={props.knowledgelist.summary} />
                            </Form.Item>
                            <Form.Item name={'isCommentable'} label="评论">
                                <Switch defaultChecked={props.knowledgelist.isCommentable} onChange={onChange} />
                            </Form.Item>
                            <Form.Item name={'cover'} label="封面">
                                {url ? <div  style={{background:`url(${url}) no-repeat center`}}> <Dragger {...propsOver} >                                                                  
                                   <div style={{background:`url(${url}) center `,backgroundSize:'cover',width:'100%',height:'120px'}}></div>
                                </Dragger></div>:<div> <Dragger {...propsOver}  >
                                    <p className="ant-upload-drag-icon">
                                        <InboxOutlined />
                                    </p>
                                    <p className="ant-upload-text">点击选择文件或将文件拖拽到此处</p>
                                    <p className="ant-upload-text">
                                        文件将上传到 OSS, 如未配置请先配置
                                    </p>
                                </Dragger></div>}
                            </Form.Item>
                            <Form.Item>
                                <Input ref={myRef} value={url} />
                            </Form.Item>
                            <Form.Item >
                                <Button onClick={showChildrenDrawer} style={{marginRight:'10px'}}>
                                    选择文件
                                </Button>
                                {
                                    url ? <Button onClick={moveOutInputValue} danger>
                                        移除
                                    </Button> : null
                                }

                                <Drawer
                                    title="文件选择"
                                    width={693}
                                    closable={false}
                                    onClose={onChildrenDrawerClose}
                                    visible={childrenDrawer}
                                    zIndex={3333}
                                    getContainer={false}
                                    extra={
                                        <Space>
                                            <span onClick={onChildrenDrawerClose} style={{ fontSize: '20px' }}>x</span>
                                        </Space>
                                    }
                                >
                                    {/* 第二个抽屉 */}
                                    <div className={styles.childDrawer}>
                                        <div className={styles.drawer_top}>
                                            <div>
                                                <div className={styles.onelabel}>
                                                    <label htmlFor="pageTile">文件名:</label><Input type="text" placeholder='请输入文件名' id='pageTile' />
                                                </div>
                                                <div className={styles.twolabel}>
                                                    <label htmlFor="pageTile">文件类型:</label><Input type="text" placeholder='请输入文件类型' id='pageTile' />
                                                </div>
                                            </div>
                                            <div className={styles.btns}>
                                                <Button type='primary'>
                                                    <span>搜索</span>
                                                </Button>
                                                <Button>
                                                    <span>重置</span>
                                                </Button>
                                            </div>
                                        </div>
                                        <div className={styles.drawer_main}>
                                            <div className={styles.upload}>
                                                <Button>上传文件</Button>
                                            </div>
                                            <div className={styles.list_box_drawer}>
                                                {
                                                    KnowledgeDrawerFile && KnowledgeDrawerFile.map((item) => {
                                                        return <div className={styles.box}>
                                                            <div className={styles.inset}>
                                                                <Image src={item.url} alt="" height='120px' width='100%' />
                                                                <div>
                                                                    <span onClick={()=>changeUrl(item.url)}>{item.originalname}</span>
                                                                </div>
                                                            </div>

                                                        </div>
                                                    })
                                                }

                                            </div>
                                            <div className={styles.drawerPagination}>
                                                <Pagination
                                                    total={KnowledgeDrawerFileLength}
                                                    showTotal={total => `共 ${total} 条`}
                                                    defaultPageSize={12}
                                                    defaultCurrent={1}
                                                    onChange={drawerChange}
                                                />
                                            </div>

                                        </div>
                                    </div>
                                </Drawer>

                            </Form.Item>
                        </Form>
                    </div>
                </Drawer>
            </div>
        </div>
    </div>
}
export default KnowledgeBox;